package com.ssy.lingxi.purchase.entity.converter;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.purchase.entity.PurchaseNeedPlanDetail;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.ArrayList;
import java.util.List;

/**
 * 将自定义的采购需求计划明细Entity，与表中的Jsonb字段进行转换
 * @author fhj
 * @date 2021/03/03
 * @version 2.0.0
 * */
@Converter(autoApply = true)
public class JpaJsonToPurchaseNeedPlanDetailConverter implements AttributeConverter<List<PurchaseNeedPlanDetail>, String> {
    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(List<PurchaseNeedPlanDetail> attribute) {
        try {
            return OBJECT_MAPPER.writeValueAsString(attribute);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR,"省市区域转换Json错误");
        }
    }

    @Override
    public List<PurchaseNeedPlanDetail> convertToEntityAttribute(String dbData) {
        try {
            if(dbData == null) {
                return new ArrayList<>();
            }

            return OBJECT_MAPPER.readValue(dbData, new TypeReference<List<PurchaseNeedPlanDetail>>() {});
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR,"数据库json字段转换省市区域实体错误");
        }
    }
}
